<template>
  <div className="call_chain_page" :style="isFullScreen ? fullScreenStyle : {}">
    <header className="flex-spb-center">
      <ga-button @click="changeAttachDataType"
        :disabled="+new Date(queryTime.to) - +new Date(queryTime.from) > MaxTime">
        {{ attachDataType ? "切换为环比数据" : "切换为同比数据" }}
      </ga-button>
      <div className="flex">
        <ga-select placeholder="选择POD名称搜索" :style="{ width: '210px' }" class="mr8" allowClear showArrow showSearch
          :filterOption="(input, option) =>
            (option?.label ?? '').toLowerCase().includes(input.toLowerCase())
            " @change="onSearchNode" @clear="() => onSearchNode('')">

          <ga-option v-for="node in topoData.nodes" :value="node.id" :label="node.podName" :key="node.id">
            <div :style="{ ...statusDotStyle, background: statusColorMap[getNodeAndEdgeStatus(node)], }">


            </div>
            {{ node.podName }}
          </ga-option>

        </ga-select>
        <ga-button @click="() =>
          isFullScreen = !isFullScreen
          ">
          <template #icon>
            <icon-fullscreen v-show="!isFullScreen" />
            <icon-fullscreen-exit v-show="isFullScreen" />
          </template>
        </ga-button>
      </div>
    </header>
    <PodTopo ref="topoRef" :topoData="topoData" :isFullScreen="isFullScreen" :queryTime="queryTime" />
  </div>
</template>

<script setup>
import { onMounted, ref, watch } from 'vue';
import { forEach, isEmpty, map } from 'lodash'
import PodTopo from './PodTopo.vue';
import { MaxTime, statusColorMap, statusDotStyle, fullScreenStyle } from './staticData';
import { clearAllStats, getNodeAndEdgeStatus, graphFocusNode } from './utils';
import { useRoute } from 'vue-router';
import { bus } from '@/utils/eventBus';
import { getPodTopologyGraph, systemTopoGraph } from '@/api/topoNodeDetail';

const props = defineProps({
  node: {
    type: Object,
    default: () => ({})
  },
  queryTime: {
    type: Object,
    default: () => ({})
  },
  visible: Boolean,
  tab: String,
})
const { query } = useRoute()
const topoRef = ref()
const isFullScreen = ref(false)
const attachDataType = ref(0)  // 展示同环比数据 0-环比 1-同比
const fetching = ref(false)
const topoData = ref({ nodes: [], edges: [] })
// 获取拓扑数据
const getTopoData = (props) => {

  const { node, queryTime } = props;
  if (isEmpty(node) || fetching.value) {
    return;
  }
  const { systemId } = query

  const { from, to } = queryTime;

  console.log(node,);

  const params = {
    masterIp: node.masterIp,
    namespace: node.namespace,
    workloadName: node.workloadName,
    workloadType: node.workloadKind,
    from,
    to,
    systemId,
  };
  fetching.value = true
  const req = systemId ? systemTopoGraph(params) : getPodTopologyGraph(params)
  // * 避免vm无限嵌套调用链
  const nodeKind = node.workloadKind;

  req.then((res) => {
    const { instance: apiNodes, edge: apiEdges } = res.data;
    const nodes = map(apiNodes, (node) => {
      return {
        ...node,
        id: node.workloadKey,
        x: node.xaxis,
        y: node.yaxis,
        topoViewType: "pod",
        attachDataType: attachDataType.value,
        isHideCallChain: nodeKind === 'vm'
      };
    });
    const edges = map(apiEdges, (edge) => {
      return {
        ...edge,
        source: edge.srcPodKey,
        target: edge.dstPodKey,
        attachDataType: attachDataType.value,
      };
    });
    fetching.value = false
    topoData.value = { nodes, edges }
  });
};
// 改变同环比的显示
const changeAttachDataType = () => {
  const attachDataTypeVal = attachDataType.value
  if (topoRef.value?.graph) {
    const graph = topoRef.value.graph;
    graph.setAutoPaint(false);
    const nodes = graph.getNodes();
    const edges = graph.getEdges();
    forEach(nodes, (node) => {
      const nodeModel = node.getModel();
      nodeModel.attachDataType = attachDataTypeVal ? 0 : 1;
      graph.updateItem(node, nodeModel);
    });
    forEach(edges, (edge) => {
      const edgeModel = edge.getModel();
      edgeModel.attachDataType = attachDataTypeVal ? 0 : 1;
      const edgeStatus = getNodeAndEdgeStatus(edgeModel);
      edgeModel.style.stroke = edgeStatus ? "#F7313B" : "#AAAAAA";
      edgeModel.style.endArrow.fill = edgeStatus
        ? "#F7313B"
        : "#AAAAAA";
      graph.updateItem(edge, edgeModel);
    });
    graph.paint();
    graph.setAutoPaint(true);
  }
  attachDataType.value = attachDataTypeVal ? 0 : 1;

};
// 搜索节点
const onSearchNode = (value) => {
  // console.log(topoRef.value, 'topoRef');

  if (!topoRef.value?.graph) {
    return;
  }
  const graph = topoRef.value.graph;
  // 清除所有节点状态
  if (!value) {
    clearAllStats(graph);
    return;
  }
  if (value) {

    const searchNode = topoData.value.nodes.find(({id}) => id === value);
    clearAllStats(graph);

    const searchNodeItem = graph.findById(searchNode?.id);
    graphFocusNode(searchNodeItem, graph, true);

    graph.setItemState(searchNodeItem, "hover", true);
  }
}
onMounted(() => {
  getTopoData(props)
  bus.on('updateTopoNodeDetail', () => {
    getTopoData(props)
  })
})
watch([() => props.node, () => props.queryTime], (newV) => {
  getTopoData(props)
})
</script>

<style scoped lang="scss">
.call_chain_page {
  height: 76vh;
  display: flex;
  flex-direction: column;
  background-color: white;
}
</style>
